#include <iostream>
using std::cout;
using std::endl;

class Data
{
public:
    Data()
    {
        cout << "Data()" << endl;
    }
    ~Data()
    {
        cout << "~Data()" << endl;
    }

    int getData() const{ return _data; }
private:
    int _data = 10;
};

class MiddleLayer
{
public:
    MiddleLayer(Data * p)
    : _pdata(p)
    {
        cout << "MiddleLayer(Data*)" << endl;
    }

    ~MiddleLayer(){
        cout << "~MiddleLayer(Data*)" << endl;
        if(_pdata){
            delete _pdata;
            _pdata = nullptr;
        }
    }

    Data * operator->(){
        return _pdata;
    }

    Data & operator*(){
        return *_pdata;
    }

    friend class ThirdLayer;
private:
    Data * _pdata;
};

class ThirdLayer
{
public:
    ThirdLayer(MiddleLayer * pml)
    : _pml(pml)
    {
        cout << "ThirdLayer(MiddleLayer*)" << endl;
    }

    ~ThirdLayer(){
        cout << "~ThirdLayer(MiddleLayer*)" << endl;
        if(_pml){
            delete _pml;
            _pml = nullptr;
        }
    }

    MiddleLayer & operator->(){
        return *_pml;
    }

    //一步一步解引用
    /* MiddleLayer & operator*(){ */
    /*     return *_pml; */
    /* } */

    //一步到位解引用
    Data & operator*(){
        /* return *(*_pml); */
        /* return (*_pml).operator*(); */
        return *((*_pml)._pdata);//需要友元的支持
    }
private:
    MiddleLayer * _pml;
};


void test0(){
    ThirdLayer tl(new MiddleLayer(new Data()));

    cout << tl->getData() << endl;

    //一步一步解引用
    /* cout << ((tl.operator*()).operator*()).getData() << endl; */
    /* cout << (*(*tl)).getData() << endl; */

    //一步到位解引用
    /* cout << tl.operator*().getData() << endl; */
    cout << (*tl).getData() << endl;
}

int main(void){
    test0();
    return 0;
}
